import { Asset, AssetManager, assetManager, Constructor } from "cc";
/** 单例模式的资源管理器 */
export class ResManager {
    /**
     * 加载 Asset Bundle 接口
     * @param bundleName Asset Bundle 的名称
     * @param cb 可选回调
     */
    loadBundle(bundleName: string, cb?: (bundle: AssetManager.Bundle | null) => void) {
        assetManager.loadBundle(bundleName, (e, bundle) => {
            cb && cb(bundle);
        });
    }

    /**
     * 加载 Asset Bundle 接口
     * @param bundleName 
     * @returns 
     */
    loadBundleAsync(bundleName: string): Promise<AssetManager.Bundle> {
        return new Promise<AssetManager.Bundle>(rs => this.loadBundle(bundleName, rs))
    }

    loadAsset<T extends Asset>(bUrl: IBundleUrl, type: Constructor<T> | null, cb: (asset: T | null) => void) {
        assetManager.loadBundle(bUrl.b, (e, bundle) => {
            bundle.load(bUrl.l, type, (err, _asset) => {
                if (err) {
                    console.error(err);
                    return cb(null);
                }
                cb(_asset)
            })
        })
    }

    loadAssetAsync<T extends Asset>(bUrl: IBundleUrl, type: Constructor<T> | null) {
        return new Promise<T>(rs => this.loadAsset(bUrl, type, rs as any))
    }

    getAsset<T extends Asset>(bUrl: IBundleUrl, type?: Constructor<T> | null): T {
        let assetBundle = assetManager.getBundle(bUrl.b);
        return assetBundle.get(bUrl.l, type)
    }
}